package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.gulimall.search.config.GulimallElasticSearchConfig;
import com.atguigu.gulimall.search.constant.ESConstant;
import com.atguigu.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {
    @Override
    public Boolean ProductSave(List<SkuEsModel> skuEsModelList) throws IOException {

        //1. 创建索引,即在kibana中创建索引

        //2. 给ES中保存数据
        BulkRequest bulkRequest = new BulkRequest();

        for (SkuEsModel skuEsModel : skuEsModelList) {
            IndexRequest indexRequest = new IndexRequest();
            indexRequest.index(ESConstant.Product_Index);
            indexRequest.id(skuEsModel.getSkuId().toString());
            // 使用fastjson的方法将对象转化为json数据
            String s = JSON.toJSONString(skuEsModel);
            indexRequest.source(s, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }

        RestHighLevelClient esRestClient = new GulimallElasticSearchConfig().esRestClient();
        BulkResponse responses = esRestClient.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);

        // TODO 如果批量保存错误,说明就是索引建立的有问题或者ES出现问题
        // 将错误信息打印一下,并且成功或者失败返回一个布尔值
        boolean b = responses.hasFailures();

        if(b){
            List<Integer> collect = Arrays.stream(responses.getItems()).map(item -> {
                return item.getItemId();
            }).collect(Collectors.toList());
            log.error("商品上架错误:{}" + collect);
        }
        return b;

    }
}
